<template>
  <div class="dashboard-container">

    <!-- 顶部操作栏 -->
    <div class="search">
      <el-form :inline="true" class="left">
        <el-form-item>
          <el-button type="primary" @click="handleAdd('create')">
            <i class="el-icon-plus"></i>
            新增
          </el-button>
        </el-form-item>
        <!-- <el-form-item>
          <el-button type="danger" @click="getData">
            <i class="el-icon-delete-solid"></i>
            删除
          </el-button>
        </el-form-item> -->
      </el-form>
      <el-form :inline="true" :model="params" class="right">
        <el-form-item>
          <el-select v-model="params.departmentId" style="width: 100%;" filterable clearable placeholder="请选择部门">
            <el-option v-for="item in roleList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input placeholder="请输入账号" v-model="params.loginName" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-input placeholder="请输入手机号" v-model="params.phone" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" plain @click="handleSearch">
            查询
            <i class="el-icon-search"></i>
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 内容栏 -->
    <div class="body">

      <!-- 列表 -->
      <el-table :data="list" v-loading="loading">
        <el-table-column label="真实姓名" prop="realName"></el-table-column>
        <el-table-column label="入职时间" prop="entryTimeName"></el-table-column>
        <el-table-column label="部门" prop="department.name"></el-table-column>
        <el-table-column label="账号" prop="loginName"></el-table-column>
        <el-table-column label="手机号" prop="phone"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="{row}">
            <el-tag type="success" v-if="row.enabled==1">正常</el-tag>
            <el-tag type="danger" v-else>禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="230px">
          <template slot-scope="{row}">
            <el-button type="text" @click="handleAdd('update', row)">
              <i class="el-icon-edit-outline"></i>
              编辑
            </el-button>
            <el-button type="text danger" @click="handleDelete(row.id)">删除</el-button>
            <el-button type="text" @click="handleEnable(row.id, 1)" v-if="row.enabled!=1">启用</el-button>
            <el-button type="text danger" @click="handleEnable(row.id, 0)" v-else>禁用</el-button>
            <el-button type="text danger" @click="handleRestPass(row.id)">重置密码</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="page">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="params.pageIndex+1"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="params.pageCount"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>

    </div>

    <!-- 新增、编辑 -->
    <el-dialog 
      top="50px"
      :visible.sync="dialogVisible" 
      :close-on-click-modal="false"
      @close="dialogVisible=false"
      :title="dialogType=='create'?'创建用户':'编辑用户'"
      width="600px"
    >
      <el-form ref="form" :rules="rules" :model="temp">
        <el-form-item label="真实姓名" prop="realName">
          <el-input placeholder="请输入真实姓名" v-model="temp.realName"></el-input>
        </el-form-item>
        <el-form-item label="登录账号" prop="loginName">
          <el-input placeholder="请输入登录账号" v-model="temp.loginName"></el-input>
        </el-form-item>
        <!-- <el-form-item label="选择角色" prop="name">
          <el-select v-model="temp.role" style="width: 100%;">
            <el-option v-for="item in roleList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="选择部门" prop="departmentId">
          <el-select v-model="temp.departmentId" style="width: 100%;" filterable clearable>
            <el-option v-for="item in roleList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input placeholder="请输入手机号" v-model="temp.phone"></el-input>
        </el-form-item>
        <el-form-item label="入职时间" prop="entryTime">
          <el-date-picker
            v-model="temp.entryTime"
            type="date"
            placeholder="选择日期"
            style="width: 100%;"
            value-format="timestamp"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit('form')">提交</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { userCreate, userUpdate, userGetList, userDelete, userResetPassword } from '@/api/user'
import { departmentGetList } from '@/api/department'
import moment from 'moment'
import md5 from 'js-md5'

export default {
  name: 'Staffuser',
  computed: {
    ...mapGetters([
      'name'
    ])
  },
  data(){
    return {
      rules: {
        realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
        departmentId: [{ required: true, message: '请选择部门', trigger: 'blur' }],
        entryTime: [{ required: true, message: '请选择入职时间', trigger: 'blur' }],
        loginName: [{ required: true, message: '请输入登录账号', trigger: 'blur' }],
        phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
      },
      params: {
        enabled: '',
        companyId: 1,
        userId: '',
        pageCount: 10,
        pageIndex: 1,
        phone: '',
        realName: '',
        type: 1, // 1员工 2客户
      },
      total: 0,
      list: [],
      dialogVisible: false,
      dialogType: 'create',
      temp: {
        realName: '',
        companyId: 1,
        type: 1,
        departmentId: '',
        entryTime: '',
        loginName: '',
        phone: ''
      },
      loading: false,
      roleList: []
    }
  },
  mounted(){
    this.getDepartment();
    this.handleSearch();
    
  },

  methods:{
    // 禁用启用
    async handleEnable(id, enabled){
      await userUpdate({ id, enabled })
      this.$message.success({ message: '操作成功' })
      this.getData();
    },
    // 获取部门列表
    async getDepartment(){
      let data = await departmentGetList({companyId: 1,pageCount: 1000,pageIndex: 0})
      this.roleList = data.list.map(item=>{
        return { label: item.name, value: item.id }
      })
    },
    //重置密码
    async handleRestPass(id){
        this.$prompt('请输入重置后的密码', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(async ({ value }) => {
          // coding...
          await userResetPassword({ id, password: md5(value).toUpperCase() })
          this.$message({
            type: 'success',
            message: '重置成功'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入'
          });       
        });

      
    },
    // 点击删除
    handleDelete(id){
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await userDelete({ id })
        this.getData();
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    //提交表单
    submit(formName){
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          if(this.dialogType =='create'){
            await userCreate(this.temp)
            this.$message.success('创建成功')
          }else{
            await userUpdate(this.temp)
            this.$message.success('修改成功')
          }
          this.handleSearch();
          this.dialogVisible = false;
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 点击新增、编辑
    handleAdd(type, row){
      this.dialogType = type;
      this.dialogVisible = true;
      if(type=='create'){
        this.temp = {
          realName: '',
          companyId: 1,
          type: 1,
          departmentId: '',
          entryTime: '',
          loginName: '',
          phone: ''
        }
      }else{
        this.temp = JSON.parse(JSON.stringify(row))
      }
    },
    //修改搜索条件
    handleSearch(){
      this.params.pageIndex = 0;
      this.getData();
    },
    //加载列表数据
    async getData(){
      this.loading = true
      let data = await userGetList(this.params)
      this.loading = false;
      this.total = data.totalCount;
      this.list = data.list.map(item=>{
        item.createTime = moment(item.createTime).format('YYYY-MM-DD HH:mm:ss')
        item.entryTimeName = moment(item.entryTime).format('YYYY-MM-DD')
        return item;
      });
    },
    // 修改每页数量
    handleSizeChange(val){
      this.params.pageIndex = 0;
      this.params.pageCount = val;
      this.getData();
    },
    // 切换分页
    handleCurrentChange(val){
      this.params.pageIndex = val - 1;
      this.getData();
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard {
  &-container {
    margin: 30px;
    position: relative;
    .right{
      position: absolute;
      right: 0;
      top: 0;
    }

    .page{
      padding: 20px 0;
      text-align: center;
    }
  }
  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}
</style>
